import {
  searchDynamicForm,
  searchPlatformDynamicForm,
  dynamicFormRebuildingRow,
  dynamicPlatformFormRebuildingRow
} from '@/api/dynamic-form';

// 获取表格prop字段
export function getTableProp(item) {
  const _info = item.info || item || {};
  return _info.field?.split('.')?.[1];
}

// 获取表单prop字段
export function getFormProp(item, index) {
  return `${index}.${getTableProp(item)}`;
}

// 拿到该行数据
export function getColumnInfo(row, item) {
  return row?.[getTableProp(item)]?.info || {};
}

// 是否是必填
export function isRequired(item) {
  return item?.info?.rules?.required ? true : false;
}

// 设置表单rules
export function setRules(row, item) {
  const _row = getColumnInfo(row, item);
  const _rules = _row?.rules || {};
  const _info = _row || {};
  const formRules = [];
  // 必填校验
  if (isRequired(item)) {
    // formRules.push({
    //   required: true,
    //   message: `${_info.name}为必填项`,
    //   trigger: 'change'
    // });
  }
  return formRules;
}

// 设置下拉属性disabled
export function setDisabled(list) {
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    item.disabled = item.available === false;
    if (item.children?.length) setDisabled(item.children);
  }
}

// 获取下拉、单选、多选、级联组件的列表
export function getOptions({ item, form_uni_key, form_role, initValues }) {
  if (item.options?.length) {
    setDisabled(item.options);
    return;
  }
  item.optionLoading = true;
  const api = {
    company: searchDynamicForm,
    platform: searchPlatformDynamicForm
  }[form_role];
  api({
    form_uni_key,
    field_name: item.info.field,
    values: initValues()
    // search:'' // 搜索的内容 远程搜索可能会用到 目前没有远程搜索
  })
    .then(res => {
      item.options = res.data || [];
      setDisabled(item.options);
    })
    .finally(() => {
      item.optionLoading = false;
    });
}

// 处理下拉事件
export function changeSelect(columnInfo, tableFormData, opts) {
  const { oldValue, domRef, row, tableData } = opts;
  const _info = columnInfo || {};
  if (!_info.field_value_type?.includes('[]')) {
    domRef?.value?.blur?.();
    domRef?.value?.togglePopperVisible?.(false);
  }
  const _change = _info.change || {};
  if (_change.change_alert && oldValue) {
    ElMessageBox({
      title: '提示',
      dangerouslyUseHTMLString: true,
      message: _change.message,
      type: 'warning',
      confirmButtonText: '确认',
      showCancelButton: true
    })
      .then(() => {
        afterAlert(columnInfo, tableFormData, { ...opts, _change });
      })
      .catch(() => {
        const index = tableData.findIndex(item => item.tableId === row.tableId);
        tableFormData[index][getTableProp(columnInfo)] = oldValue;
      });
    return;
  } else {
    afterAlert(columnInfo, tableFormData, { ...opts, _change });
  }
}

// 提醒后的流程
function afterAlert(columnInfo, tableFormData, opts) {
  const { topExpose, formData, _change } = opts;
  const _info = columnInfo || {};
  // 清除维格云
  if (_change.actions?.includes('clear_vika')) {
    topExpose.events?.clearVika();
  }
  // 清除字段
  if (_change.actions?.includes('clear_fields')) {
    clearFields(_change.clear_fields, formData, topExpose, tableFormData, opts);
  }
  // 表格内只刷新该行
  if (_info.re_rendering) {
    setTimeout(() => {
      renderRow(columnInfo, tableFormData, opts);
    }, 0);
  }
}

// 刷新某行
function renderRow(columnInfo, tableFormData, opts) {
  const { row, tableData, topExpose, tableInfo, formInfo } = opts;
  const index = tableData.findIndex(item => item.tableId === row.tableId);
  const values = topExpose.initValues();
  row.renderLoading = true;
  const api = {
    company: dynamicFormRebuildingRow,
    platform: dynamicPlatformFormRebuildingRow
  }[topExpose.form_role];
  api({
    form_uni_key: topExpose.form_uni_key,
    table_field_name: tableInfo.field,
    values,
    row: values.find(item => item.field === tableInfo.field)?.field_value?.[
      index
    ]
  })
    .then(res => {
      const index = tableData.findIndex(item => item.tableId === row.tableId);
      const obj = {};
      (res.data.row || []).forEach(item => {
        const _prop = getTableProp(item);
        obj[_prop] = item.info?.value;
        row[_prop].info = item.info;
      });
      tableFormData[index] = obj;
      const tableItem = formInfo.table[index];
      tableItem.forEach(item => {
        const _info = item.info;
        _info.value = obj[getTableProp(item)];
      });
    })
    .finally(() => {
      row.renderLoading = false;
    });
}

// 清除字段
function clearFields(clear_fields, formData, topExpose, tableFormData, opts) {
  if (!clear_fields?.length) return;
  const formList = topExpose.formList.value || [];
  const { row, tableData } = opts;
  const index = tableData.findIndex(item => item.tableId === row.tableId);
  tableFormData[index].is_cleareds = [];
  clear_fields.forEach(async field => {
    const formInfo = deepList(formList, field);
    formInfo.info.is_cleared = true;
    if (formInfo.info.field_type === 'table') {
      if (formInfo.table?.length) formInfo.table.length = 0;
      await nextTick();
      formData[field].length = 0;
    } else if (field.includes('.')) {
      const field_2 = field.split('.')[1];
      tableFormData[index][field_2] = undefined;
      tableFormData[index].is_cleareds.push(field_2);
    } else {
      delete formData[field];
    }
  });
}

function deepList(list, field) {
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    if (item.info?.field === field) return item;
    if (item.children?.length) {
      const obj = deepList(item.children, field);
      if (obj) return obj;
    }
  }
}

// 是否可以添加
export function canAdd(_rules, _info) {
  return (
    !_info.read_only &&
    !_info.disabled &&
    _rules.max_array &&
    _rules.max_array > _rules.min_array
  );
}
